//
//  TL_SettingViewController.m
//  WXReader
//
//  Created by Andrew on 2018/7/11.
//  Copyright © 2018年 Andrew. All rights reserved.
//

#import "TL_SettingViewController.h"

#import "TL_SettingSwitchTableViewCell.h"
#import "TL_SettingNormalTableViewCell.h"
#import "TL_SettingLogoutTableViewCell.h"

#import "AppDelegate.h"

#import "CGAboutUs_VC.h"
#import "TLNewAboutMeViewController.h"

@interface TL_SettingViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSArray<NSArray <NSString *>*> *sourcesArray;


@end

@implementation TL_SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initialize];
    [self createSubviews];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setStatusBarDefaultStyle];
}

- (void)dealloc {
    [kNotification removeObserver:self.mainTableViewGroup];
}

- (void)initialize
{
    [self setNavigationBarTitle:WXLocalizedString(@"设置")];
    self.view.backgroundColor = kGrayViewColor;
}

- (void)createSubviews
{
    self.mainTableViewGroup.delegate = self;
    self.mainTableViewGroup.dataSource = self;
    [self.view addSubview:self.mainTableViewGroup];
    
    [self.mainTableViewGroup mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(PUB_NAVBAR_HEIGHT);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.height.mas_equalTo(SCREEN_HEIGHT - PUB_NAVBAR_HEIGHT);
    }];
    
    [self refreshTableView];
}

- (void)refreshTableView {
    NSMutableArray *t_arr = [NSMutableArray array];

    [t_arr addObject:@[WXLocalizedString(@"清除缓存"), WXLocalizedString(@"好评支持"), WXLocalizedString(@"关于我们")]];

    if (TL_UserInfoManager.isLogin) {
        [t_arr addObject:@[WXLocalizedString(@"退出登录")]];
    }
    self.sourcesArray = [t_arr copy];

    
    [self.mainTableViewGroup reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sourcesArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self.sourcesArray wx_objectOrNilAtIndex:section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (TL_UserInfoManager.isLogin) {

        
        return [self createSettingNormalCellWithTableView:tableView indexPath:indexPath];
    } else {
        
        return [self createSettingNormalCellWithTableView:tableView indexPath:indexPath];
    }
    return [self createSettingNormalCellWithTableView:tableView indexPath:indexPath];
}

- (UITableViewCell *)createSettingSwitchCellWithTableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath isAutoSub:(BOOL)autosub
{
    TL_SettingSwitchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TL_SettingSwitchTableViewCell0"];
    
    if (!cell) {
        cell = [[TL_SettingSwitchTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TL_SettingSwitchTableViewCell0"];
    }
    cell.leftTitleText = [[self.sourcesArray wx_objectOrNilAtIndex:indexPath.section] objectOrNilAtIndex:indexPath.row];
    cell.hiddenEndLine = YES;
    
    if (autosub) {
        if ([TL_UserInfoModel shareInstance].auto_sub) {
            [cell.switchButton setDefaultOnState:YES];
        } else {
            [cell.switchButton setDefaultOnState:NO];
        }
        
    }
    
    NSNumber *isAuto = [[NSUserDefaults standardUserDefaults] objectForKey:IS_AUTO_BUY_NEXT_CHAPTER];
    
    if (isAuto.intValue==1) {
        [cell.switchButton setDefaultOnState:YES];
    }else{
        [cell.switchButton setDefaultOnState:NO];
    }
    
    MK_WEAK_SELF
    cell.switchButton.didChangeHandler = ^(BOOL isOn) {
        [[NSUserDefaults standardUserDefaults] setObject:@(isOn) forKey:IS_AUTO_BUY_NEXT_CHAPTER];
    };
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (UITableViewCell *)createSettingLogoutCellWithTableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath
{
    TL_SettingLogoutTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TL_SettingLogoutTableViewCell"];
    
    if (!cell) {
        cell = [[TL_SettingLogoutTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TL_SettingLogoutTableViewCell"];
    }
    cell.leftTitleText = [[self.sourcesArray wx_objectOrNilAtIndex:indexPath.section] objectOrNilAtIndex:indexPath.row];
    cell.hiddenEndLine = [[self.sourcesArray wx_objectOrNilAtIndex:indexPath.section] count] - 1 == indexPath.row;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (UITableViewCell *)createSettingNormalCellWithTableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath
{
    TL_SettingNormalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TL_SettingNormalTableViewCell"];
    
    if (!cell) {
        cell = [[TL_SettingNormalTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TL_SettingNormalTableViewCell"];
    }
    cell.leftTitleText = [[self.sourcesArray wx_objectOrNilAtIndex:indexPath.section] objectOrNilAtIndex:indexPath.row];
    if ([cell.leftTitleText isEqualToString:WXLocalizedString(@"深色模式")]) {
        cell.rightTitleText = [self userInterfaceStyleString];
    }
    cell.hiddenEndLine = NO;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

//section头部间距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kHalfMargin;
}
//section头部视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

//section底部间距
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}
//section底部视图
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TL_SettingBasicTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    
    if ([cell.leftTitleText isEqualToString:WXLocalizedString(@"清除缓存")]) {
        TL_AlertView *alert = [[TL_AlertView alloc] init];
        alert.alertViewDetailContent = WXLocalizedString(@"是否清除缓存信息");
        alert.confirmButtonClickBlock = ^{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"清除缓存成功")];
            });
        };
        [alert showAlertView];
        return;
    }
    
    if ([cell.leftTitleText isEqualToString:WXLocalizedString(@"好评支持")]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:WX_EvaluationAddress] options:@{} completionHandler:nil];
        return;
    }
    
    if ([cell.leftTitleText isEqualToString:WXLocalizedString(@"关于我们")]) {
        
        TLNewAboutMeViewController *vc = [[TLNewAboutMeViewController alloc] init];
//        vc.type = CGImagesVCType_AboutUshelper;
        [self.navigationController pushViewController:vc animated:YES];
        
        return;
    }
    
    if ([cell.leftTitleText isEqualToString:WXLocalizedString(@"退出登录")]) {
        [TL_UserInfoManager logout];
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
}

- (void)tableView:(UITableView *)tableView settingLogoutdidSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [TL_LoginViewController presentLoginView:nil];
}

- (void)autoSubNetRequest {
//    [TL_NetworkRequestManger POST:Auto_Sub_Chapter parameters:nil model:nil success:^(BOOL isSuccess, NSDictionary *_Nullable t_model, TL_NetworkRequestModel *requestModel) {
//        if (isSuccess) {
//            BOOL autoSub = [t_model[@"data"][@"auto_sub"] boolValue];
//            TL_UserInfoManager.updateWithDict(@{KEY_PATH(TL_UserInfoModel.shareInstance, auto_sub):@(autoSub)});
//        }
//    } failure:nil];
}

- (NSString *)userInterfaceStyleString {
//    switch (LLDarkManager.userInterfaceStyle) {
//        case LLUserInterfaceStyleUnspecified:
//            return WXLocalizedString(@"跟随系统");
//        case LLUserInterfaceStyleLight:
            return WXLocalizedString(@"未开启");
//        case LLUserInterfaceStyleDark:
//            return WXLocalizedString(@"已开启");
//    }
}

@end
